--[[
	Lysidia's Casting Bar Timer
	
	Very simple addon to provide a timer to the standard casting bar frame, also support the "mirror" bar.

	No Configuration, install and go.
]]

CastingBarTimer_DisplayString = " (%0.2fs)";

-- Function: Add count down timer to the Cast/Channelling Bar Frame.
function LysCastingBarFrame_OnUpdate( self, ... )
	local _, _, _, worldLatency	= GetNetStats();
	if (worldLatency == nil) then
		worldLatency = 0;
	end
	worldLatency = worldLatency / 1000;

	local timerValue		= self.maxValue - self.value - worldLatency;
	local textDisplay		= getglobal(self:GetName().."Text")

	local _, text, displayName;

	if ( self.casting ) then
		_, _, text = UnitCastingInfo(self.unit);
	elseif ( self.channeling ) then
		_, _, text = UnitChannelInfo(self.unit);
		timerValue = self.value;
	end

	if ( text ) then
		displayName = text..CastingBarTimer_DisplayString;
	end

	if (displayName ~= nil) then
		if (timerValue) then
			if (timerValue > 0.01) then
				textDisplay:SetText( format(displayName, timerValue) );
			end
		end
	end
end

-- Function: Add count down timer to the Mirror Bar Frame
function LysMirrorBarFrame_OnUpdate(self, elapsed)
	local _, _, _, worldLatency	= GetNetStats();
	if (worldLatency == nil) then
		worldLatency = 0;
	end
	worldLatency = worldLatency / 1000;

	local text			= _G[self:GetName().."Text"];
	local displayName		= text:GetText();
	local mirrorValue		= self.value - worldLatency;

	if (displayName) then
		local tempName	= string.gsub(displayName, "(.+)", "");
		tempName	= tempName..CastingBarTimer_DisplayString;

		if ((mirrorValue) and (mirrorValue > 0.01)) then
			text:SetText( format(tempName, mirrorValue) );
		end
	end
end

-- Hook the Blizzard OnUpdate handlers, using hooksecurefunc, reduces the risk of tainting.
hooksecurefunc("CastingBarFrame_OnUpdate", LysCastingBarFrame_OnUpdate);
hooksecurefunc("MirrorTimerFrame_OnUpdate", LysMirrorBarFrame_OnUpdate);
